﻿using System.Diagnostics.CodeAnalysis;
using KinonekoSoftware.CodariaDB.Documents.Timelines;

namespace KinonekoSoftware.Studio.Pages.Theories
{
    [SuppressMessage("ReSharper", "ArrangeStaticMemberQualifier")]
    public sealed class WVCEpochViewModel : TabViewModelCore
    {
        private readonly TimeSystem     _system;
        private readonly TimelineSystem _timelineSystem;


        private bool _isSelected;

        public WVCEpochViewModel()
        {
            _system         = Platform.GetEngine<TimeSystem>();
            _timelineSystem = new TimelineSystem(_system);


            NewEpochCommand       = new ActionCommand(DoNewEpochCommand);
            EditEpochCommand      = new FuncCommand<Epoch>(DoEditEpochCommand);
            ShiftUpEpochCommand   = new FuncCommand<Epoch>(DoShiftUpEpochCommand);
            ShiftDownEpochCommand = new FuncCommand<Epoch>(DoShiftDownEpochCommand);
            RemoveEpochCommand    = new FuncCommand<Epoch>(DoRemoveEpochCommand);

            ClearLayerCommand = new ActionCommand(DoClearLayerCommand);
            PopLayerCommand   = new ActionCommand(DoPopLayerCommand);
            PushLayerCommand  = new FuncCommand<Epoch>(DoPushLayerCommand);
        }


        protected override void OnStart()
        {
            Initialize();
            base.OnStart();
        }

        //-------------------------------------------------------------
        //
        //          Abstract Methods
        //
        //-------------------------------------------------------------

        //-------------------------------------------------------------
        //
        //          Private Methods
        //
        //-------------------------------------------------------------

        private void ConfirmWhichWasTheLastOne()
        {
            for (var i = 0; i < Layers.Count; i++)
            {
                var current = Layers[i];
                current.IsLastOne = i == Layers.Count - 1;
            }
        }

        //-------------------------------------------------------------
        //
        //          Public Methods
        //
        //-------------------------------------------------------------
        public void Initialize()
        {
            _timelineSystem.RebuildEpoches();
        }

        //-------------------------------------------------------------
        //
        //          Command Handlers Methods
        //
        //-------------------------------------------------------------
        private async void DoNewEpochCommand()
        {
            //
            // 不允许添加的条件1
            if (Collection.Count >= 254)
            {
                await ViewModelBase.Danger("错误", "无法添加超过254个元素");
                return;
            }

            //
            // 不允许添加的条件2
            if (_timelineSystem.EpochLayer is not null && _timelineSystem.EpochLayer.Tier > 3)
            {
                await ViewModelBase.Danger("错误", "无法添加超过4层元素");
                return;
            }

            var r = await ViewModelBase.SingleText("新建", "为标签取个名字吧!");

            if (!r.IsFinished)
            {
                return;
            }

            _timelineSystem.Add(new Epoch
            {
                Id    = ID.GetShortID(),
                Name  = r.Value,
                Color = "#007ACC",
            });
        }


        private async void DoEditEpochCommand(Epoch target)
        {
            if (target is null)
            {
                return;
            }

            var r = await ViewModelBase.SingleText("编辑", "为标签取个名字吧!", target.Name);

            //
            //
            if (!r.IsFinished)
            {
                return;
            }

            //
            //
            target.Name = r.Value;

            //
            //
            _system.Update(target);
        }


        private void DoShiftUpEpochCommand(Epoch target)
        {
            if (target is null)
            {
                return;
            }

            _timelineSystem.ShiftUp(target);
        }


        private void DoShiftDownEpochCommand(Epoch target)
        {
            if (target is null)
            {
                return;
            }

            _timelineSystem.ShiftDown(target);
        }

        private async void DoRemoveEpochCommand(Epoch target)
        {
            if (target is null)
            {
                return;
            }

            var r = await ViewModelBase.Question("正要删除一个时间点，请选择不同的删除选项。", "仅删除当前目录", "删除当前节点和子目录");

            //
            //
            if (r == TripleSelection.Cancel)
            {
                return;
            }

            if (Epoch == target)
            {
                Epoch = null;
            }


            if (Layer == target)
            {
                _timelineSystem.PopEpochLayer();
            }

            if (r == TripleSelection.Option1)
            {
                //
                // 移动所有子元素到父级
                _timelineSystem.Remove(target);
            }
            else
            {
                _timelineSystem.RemoveSubTree(target);
            }
        }

        private void DoClearLayerCommand()
        {
            _timelineSystem.ResetEpochLayer();
            ConfirmWhichWasTheLastOne();
        }

        private void DoPopLayerCommand()
        {
            Layer = _timelineSystem.PopEpochLayer();
            ConfirmWhichWasTheLastOne();
        }

        private void DoPushLayerCommand(Epoch target)
        {
            if (target is null)
            {
                return;
            }

            _timelineSystem.PushEpochLayer(target);
            ConfirmWhichWasTheLastOne();
        }

        //-------------------------------------------------------------
        //
        //          Properties
        //
        //-------------------------------------------------------------
        public Epoch Layer
        {
            get => _timelineSystem.EpochLayer;
            set => _timelineSystem.EpochLayer = value;
        }

        public Epoch Epoch
        {
            get => _timelineSystem.Epoch;
            set
            {
                _timelineSystem.Epoch = value;
                RaiseUpdated();
            }
        }

        /// <summary>
        /// 获取或设置 <see cref="IsSelected"/> 属性。
        /// </summary>
        public bool IsSelected
        {
            get => _isSelected;
            set => SetValue(ref _isSelected, value);
        }



        public ObservableCollection<Epoch> Layers     => _timelineSystem.EpochLayerList;
        public ObservableList<Epoch>       Collection => _timelineSystem.EpochCollection;

        public ICommandEX NewEpochCommand       { get; }
        public ICommandEX EditEpochCommand      { get; }
        public ICommandEX ShiftUpEpochCommand   { get; }
        public ICommandEX ShiftDownEpochCommand { get; }
        public ICommandEX RemoveEpochCommand    { get; }


        public ICommandEX ClearLayerCommand { get; }
        public ICommandEX PopLayerCommand   { get; }
        public ICommandEX PushLayerCommand  { get; }
    }
}